package com.cntaiping.workutil.indicator;

import com.cntaiping.workutil.test.HttpUtils;
import com.cntaiping.workutil.test.JsonUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class IndicatorClient extends IndicatorService {


    public IndicatorClient(LogProfile logProfile) {
        super(logProfile);

    }

    @Override
    protected void createDaemonThread() {

        Thread daemonThread = new Thread(() -> {
            logger.info("daemon thread start success!");
            while (condition) {
                try {
                    LogRecord logRecord = BLOCKING_QUEUE.take();
                    takeQueueMessage(logRecord);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();


    }

    @Override
    public boolean offerQueueMessage(LogRecord logRecord) {
        boolean offer = false;
        try {
            logger.info("start save log");
            offer = BLOCKING_QUEUE.offer(logRecord, 2, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        return offer;


    }

    @Override
    protected void takeQueueMessage(LogRecord logRecord) {

        /**
         * 开启log接口保存
         */
        if (sendToAim()) {
            saveToMysql(logRecord);
        }

    }

    @Override
    protected boolean sendToAim() {
        return logProfile.isOpenAim();
    }

    @Override
    protected boolean sendToLogServer() {
        return logProfile.isOpenRemote();
    }

    protected void saveToMysql(LogRecord logRecord) {
        try {
            String result = HttpUtils.httpPost(logProfile.getAimLogDir(), JsonUtils.getFormatJson(logRecord), null);


            if(StringUtils.isNotBlank(result)){
                logger.error("record log save failed" + result);
            }else {
                logger.info("record log save success :[" + logRecord.getAppId() + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
